package com.buanalintas.sandals.pos.item;

import com.buanalintas.bynga.Access;
import com.buanalintas.bynga.Action;
import com.buanalintas.bynga.Controller;
import com.buanalintas.bynga.Dictionary;
import com.buanalintas.bynga.Field;
import com.buanalintas.bynga.Logger;
import com.buanalintas.bynga.Page;
import com.buanalintas.bynga.Persistence;
import com.buanalintas.bynga.Sequence;
import com.buanalintas.bynga.Template;
import com.buanalintas.bynga.Utility;
import com.buanalintas.bynga.entities.MasterUnit;
import com.buanalintas.bynga.formatter.MoneyFormatter;
import com.buanalintas.sandals.pos.entities.PosMasterItem;
import com.buanalintas.sandals.pos.entities.PosMasterItemDetail;
import com.buanalintas.sandals.pos.entities.PosMasterItemStock;
import com.buanalintas.sandals.pos.entities.PosMasterSize;
import com.buanalintas.sandals.pos.entities.PosMasterStatus;
import com.buanalintas.sandals.pos.entities.PosTransactionBarcode;
import java.util.List;
import java.util.Random;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class Item2 extends Page {

    private Field itemId;
    private Field itemColorId;
//    private Field itemSizeId;
//    private Field itemSize;
    private Field itemSupplierModelId;
    private Field itemCode;
//    private Field itemCode2;
    private Field itemModel;
    private Field itemBarcode;
    private Field itemPriceBuyId;
    private Field itemPriceBasic;
    private Field itemPriceShop;
    private Field itemPriceFranchise;
    private Field itemPriceOnlineId;
    private Action actionPrintBarcode = new Action("printBarcode", "Print Barcode");
    private Action actionPrintAllBarcode = new Action("printAllBarcode", "Print All Barcode");
    private Action actionPrintMultipleBarcode = new Action("printMultipleBarcode", "Print Multiple Barcode");

    public Item2() {
        setTheClass(PosMasterItem.class);
        setPageDetail(ItemDetail.class);

        itemId = new Field();
        itemId.setName("itemId");
        itemId.setCaption("id");
        itemId.setListProperties(" align=\"right\" width=\"5%\" nowrap");
        itemId.setInputProperties(" size=\"20\"");
        getFields().add(itemId);

        itemColorId = new Field();
        itemColorId.setName("itemColorId");
        itemColorId.setCaption("color");
        itemColorId.setListProperties(" align=\"center\" width=\"8%\" nowrap");
        itemColorId.setInputProperties(" ");
        itemColorId.setRequired(true);
        itemColorId.setInputType(Field.INPUT_COMBO_BOX);
        getFields().add(itemColorId);

//        itemSizeId = new Field();
//        itemSizeId.setName("itemSizeId");
//        itemSizeId.setCaption("size");
//        itemSizeId.setListProperties(" align=\"center\" width=\"7%\" nowrap");
//        itemSizeId.setInputProperties(" ");
//        itemSizeId.setRequired(true);
//        itemSizeId.setInputType(Field.INPUT_CHECK_BOX);
////        itemSizeId.setInputType(Field.INPUT_COMBO_BOX);
//        getFields().add(itemSizeId);
//        
//        itemSize = new Field();
//        itemSize.setName("itemSize");
//        itemSize.setCaption("size");
//        itemSize.setEntityRelation(PosMasterSize.class);
//        itemSize.setListProperties(" align=\"center\" width=\"7%\" nowrap");
//        itemSize.setInputProperties(" ");
//        itemSize.setRequired(true);
//        itemSize.setInputType(Field.INPUT_CHECK_BOX);
////        itemSizeId.setInputType(Field.INPUT_COMBO_BOX);
//        getFields().add(itemSize);

        itemSupplierModelId = new Field();
        itemSupplierModelId.setName("itemSupplierModelId");
        itemSupplierModelId.setCaption("code supplier");
        itemSupplierModelId.setListProperties(" align=\"center\" width=\"9%\" nowrap");
        itemSupplierModelId.setInputProperties(" ");
        itemSupplierModelId.getSelectorColumns().add(new String[]{"supplierModelCode", " Code", "width=\"10%\""});
        itemSupplierModelId.getSelectorColumns().add(new String[]{"supplierModelModelId", " Model", "width=\"20%\" nowrap"});
        itemSupplierModelId.getSelectorColumns().add(new String[]{"supplierModelSupplierId", " Supplier", "width=\"70%\" nowrap"});
        itemSupplierModelId.setRequired(true);
        getFields().add(itemSupplierModelId);

        itemCode = new Field();
        itemCode.setName("itemCode");
        itemCode.setCaption("code Item");
        itemCode.setListProperties(" align=\"center\" width=\"12%\" nowrap");
        itemCode.setInputProperties(" size=\"10\"");
        itemCode.setRequired(true);
        itemCode.setInputCase(Field.CASE_UPPER);
        getFields().add(itemCode);
        
//        itemCode2 = new Field();
//        itemCode2.setName("itemCode2");
//        itemCode2.setCaption("code Item 2");
//        itemCode2.setListProperties(" align=\"center\" width=\"12%\" nowrap");
//        itemCode2.setInputProperties(" size=\"10\"");
//        itemCode2.setRequired(true);
//        itemCode2.setInputCase(Field.CASE_UPPER);
//        getFields().add(itemCode2);

        itemModel = new Field();
        itemModel.setName("itemModel");
        itemModel.setCaption("model");
        itemModel.setListProperties(" align=\"center\" width=\"8%\" nowrap");
        itemModel.setInputProperties(" ");
        getFields().add(itemModel);

        itemBarcode = new Field();
        itemBarcode.setName("itemBarcode");
        itemBarcode.setCaption("barcode");
        itemBarcode.setListProperties(" align=\"center\" width=\"5%\" nowrap");
        itemBarcode.setInputProperties(" size=\"10\" style=\"text-align: right;\" readonly");
        itemBarcode.setInputCase(Field.CASE_UPPER);
        getFields().add(itemBarcode);

        itemPriceBuyId = new Field();
        itemPriceBuyId.setName("itemPriceBuyId");
        itemPriceBuyId.setCaption("price sell");
        itemPriceBuyId.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        itemPriceBuyId.setInputProperties(" ");
        itemPriceBuyId.setRequired(true);
        itemPriceBuyId.setInputType(Field.INPUT_COMBO_BOX);
        getFields().add(itemPriceBuyId);

        itemPriceBasic = new Field();
        itemPriceBasic.setName("itemPriceBasic");
        itemPriceBasic.setCaption("price basic");
        itemPriceBasic.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        itemPriceBasic.setInputProperties(" size=\"10\" style=\"text-align: right;\" onkeyup=\"__calculatePrice();\"");
        itemPriceBasic.setFormater(MoneyFormatter.getInstance());
        itemPriceBasic.setRequired(true);
        itemPriceBasic.setInputCase(Field.CASE_UPPER);
        getFields().add(itemPriceBasic);

        itemPriceShop = new Field();
        itemPriceShop.setName("itemPriceShop");
        itemPriceShop.setCaption("price shop");
        itemPriceShop.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        itemPriceShop.setInputProperties(" size=\"10\" style=\"text-align: right;\" readonly");
        itemPriceShop.setFormater(MoneyFormatter.getInstance());
        itemPriceShop.setRequired(true);
        itemPriceShop.setInputCase(Field.CASE_UPPER);
        getFields().add(itemPriceShop);

        itemPriceFranchise = new Field();
        itemPriceFranchise.setName("itemPriceFranchise");
        itemPriceFranchise.setCaption("price franchise");
        itemPriceFranchise.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        itemPriceFranchise.setInputProperties(" size=\"10\" style=\"text-align: right;\" readonly");
        itemPriceFranchise.setFormater(MoneyFormatter.getInstance());
        itemPriceFranchise.setRequired(true);
        itemPriceFranchise.setInputCase(Field.CASE_UPPER);
        getFields().add(itemPriceFranchise);

        itemPriceOnlineId = new Field();
        itemPriceOnlineId.setName("itemPriceOnlineId");
        itemPriceOnlineId.setCaption("price online");
        itemPriceOnlineId.setListProperties(" align=\"right\" width=\"6%\" nowrap");
        itemPriceOnlineId.setInputProperties(" ");
        itemPriceOnlineId.setRequired(true);
        itemPriceOnlineId.setInputType(Field.INPUT_COMBO_BOX);
        getFields().add(itemPriceOnlineId);

        fillFields();
        getActions().add(Action.TRANS_ADD);
        getActions().add(Action.TRANS_EDIT);
        getActions().add(Action.TRANS_VIEW);

        getFieldsUnique().add(new Field[]{itemCode});
        getFieldsUnique().add(new Field[]{itemBarcode});

        getFieldsAdd().remove(itemId);
        
        getFieldsAdd().remove(itemModel);
        getFieldsAdd().remove(itemCode);
//        getFieldsAdd().remove(itemSizeId);
        getFieldsEdit().remove(itemId);
        getFieldsEdit().remove(itemCode);
//        getFieldsEdit().remove(itemSizeId);
        getFieldsList().remove(itemId);
        getFieldsList().remove(itemId);
        getFieldsPrint().remove(itemId);
        getFieldsPrintList().remove(itemId);
        getFieldsView().remove(itemId);

        getFieldsSearch().remove(itemId);
        setExportList(getClass().getResourceAsStream("ItemList.jasper"));
        setExport(getClass().getResourceAsStream("Item.jasper"));
        setController(new ItemController(this));
        getController().setOrder(itemId);
        getActions().add(actionPrintBarcode);
        getActions().add(actionPrintMultipleBarcode);
        getActions().add(actionPrintAllBarcode);
    }

    @Override
    public void beforeAdd() {
        itemBarcode.setDefaultValue(cekBarcode());
    }

    private String generateBarcode() {
        Random random = new Random();
        String bcode = "" + (random.nextInt(899999) + 100000);
        String barcode;
        if (bcode.length() == 1) {
            barcode = "00000" + bcode;
        } else if (bcode.length() == 2) {
            barcode = "0000" + bcode;
        } else if (bcode.length() == 3) {
            barcode = "000" + bcode;
        } else if (bcode.length() == 4) {
            barcode = "00" + bcode;
        } else if (bcode.length() == 5) {
            barcode = "0" + bcode;
        } else {
            barcode = bcode;
        }
        return barcode;
    }

    private String cekBarcode() {
        EntityManager em = getEntityManager();
        String barcode = generateBarcode();
        try {
            Query query = em.createQuery("SELECT t PosMasterItem t WHERE t.itemBarcode =" + generateBarcode());
            List<PosMasterItem> list = query.getResultList();
            System.out.println("" + list);
            if (list.size() > 0) {
                exist();
            } else if ("000000".equals(barcode)) {
                exist();
            } else {
                return barcode;
            }
        } catch (Exception e) {
            Logger.getInstance().log(e);
        }
        return barcode;
    }

    public void exist() {
        cekBarcode();
    }

    public static PosMasterItemStock getStock(EntityManager em, PosMasterItem item, MasterUnit unit, PosMasterStatus status, PosMasterSize size) {
        try {
            Query query = em.createQuery("SELECT t FROM PosMasterItemStock t WHERE t.itemStockItemId=:itemStockItemId AND t.itemStockUnitId=:itemStockUnitId AND t.itemStockStatusId=:itemStockStatusId AND t.itemStockSizeId=:itemStockSizeId");
            query.setParameter("itemStockItemId", item);
            query.setParameter("itemStockUnitId", unit);
            query.setParameter("itemStockStatusId", status);
            query.setParameter("itemStockSizeId", size);
            return (PosMasterItemStock) query.getSingleResult();
        } catch (Exception e) {
            Logger.getInstance().log(e);
        }
        PosMasterItemStock stock = new PosMasterItemStock();
        stock.setItemStockId(Sequence.next(stock));
        stock.setItemStockItemId(item);
        stock.setItemStockUnitId(unit);
        stock.setItemStockStatusId(status);
        stock.setItemStockSizeId(size);
        stock.setItemStockValue(0);
        if (!em.getTransaction().isActive()) {
            em.getTransaction().begin();
            em.persist(stock);
            em.getTransaction().commit();
        } else {
            em.persist(stock);
        }
        return stock;
    }

    @Override
    public String addJavascript() {
        String calculate = "<script>function __calculatePrice() {"
                + "var price2 = Number(document.getElementById('itemPriceBasic').value);"
                + "document.getElementById('itemPriceShop').value = price2 + 2500;"
                + "document.getElementById('itemPriceFranchise').value = price2 + 10000;"
                + "}"
                + "function __printBarcode(id) { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionPrintBarcode.getName() + "&id=\"+id; return false; } function __printAllBarcode() { location.href = \"?m=" + getMenu().getMenuName() + "&a=" + actionPrintAllBarcode.getName() + "\";  return false; }"
                + "function __printMultipleBarcode(action, name) { "
                + "    var form = document.getElementById(name); "
                + "    var selected = false; "
                + "    for (var i=0; i < form.elements.length; i++) { "
                + "        if (form.elements[i].type == 'checkbox') { "
                + "            if (form.elements[i].checked) { "
                + "                selected = true; "
                + "                break; "
                + "            } "
                + "        } "
                + "    } "
                + "    if (!selected) { "
                + "        alert('Select data to print'); "
                + "        return false; "
                + "    } "
                + "    if (!confirm('Are you sure to print selected data?')) { "
                + "        return false; "
                + "    } "
                + "    document.getElementById('act').value = '" + actionPrintMultipleBarcode.getName() + "'; "
                + "    form.action = action; "
                + "    form.submit(); "
                + "    return false; "
                + "}</script>";
        return calculate;
    }

    
    
    class ItemController extends Controller {

        public ItemController(Page page) {
            super(page);
            
        }

        @Override
        public void beforeUpdate(Object data) {
            EntityManager em = getEntityManager();
            PosMasterItem item = (PosMasterItem) data;
            System.out.println("jose test"+data);
            item.setItemModel(item.getItemSupplierModelId().getSupplierModelModelId().getModelName());
            item.setItemCode( 
                    item.getItemColorId().getColorCode()
//                    +item.getItemSizeId().getSizeCode()
                    + item.getItemSupplierModelId().getSupplierModelCode()
//                    + item.getItemCode()
                    );
            
//            item.setItemCode2( 
////                    item.getItemColorId().getColorCode()
//                    item.getItemSizeId().getSizeCode()
////                    + item.getItemSupplierModelId().getSupplierModelCode()
//                    + item.getItemCode());
        }

        @Override
        public void beforeInsert(Object data, List list) {
            EntityManager em = getEntityManager();
            PosMasterItem item = (PosMasterItem) data;
            String[] sizes = item.getItemSize().split(",");
            item.setItemModel(item.getItemSupplierModelId().getSupplierModelModelId().getModelName());
            item.setItemCode(
                    item.getItemColorId().getColorCode()
                    + item.getItemSizeId().getSizeCode()
                    + item.getItemSupplierModelId().getSupplierModelCode()
//                    + item.getItemCode()
                    );
            for (int i = 0; i < list.size(); i++) {
                PosMasterItemDetail itemDetail = (PosMasterItemDetail) list.get(i);
                itemDetail.setItemDetailCode(
                    item.getItemSupplierModelId().getSupplierModelCode()
                    + item.getItemColorId().getColorCode()
                    + itemDetail.getItemDetailSizeId().getSizeCode());
                itemDetail.setItemDetailBarcode(
                    item.getItemSupplierModelId().getSupplierModelCode()
                    + item.getItemColorId().getColorCode()
                    + itemDetail.getItemDetailSizeId().getSizeCode());
            }
//            item.setItemCode2(
////                    item.getItemColorId().getColorCode()
//                    item.getItemSizeId().getSizeCode()
////                    + item.getItemSupplierModelId().getSupplierModelCode()
//                    + item.getItemCode());
        }
    }
    
    

    @Override
    public void beforeView() {
        beforeList();
    }

    @Override
    public void beforeExport() {
        getExportParams().put("title", Dictionary.getValue(this, "Item"));
    }

    @Override
    public void beforeExportMulti() {
        beforeExport();
    }

    @Override
    public StringBuffer processCustomRowCommand(StringBuffer template, Page page, Object data) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        if (Access.isGranted(page, actionPrintBarcode)) {
            command = new StringBuffer(template.toString());
            String encodedId = Utility.encode(Utility.getStringValue(data, page.getPrimaryKeyField()));
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintBarcode.getName() + "&id=" + encodedId);
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print Barcode"));
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printBarcode('" + encodedId + "')\"");
            Utility.replaceAll(command, Template.TABLE_ROW_MENU_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/bullet-barcode.png");
            commands.append(command.toString());
            commands.append("<input type=\"text\" class=\"form-text\" name=\"barcode_quantity_" + encodedId + "\" value=\"1\" style=\"width: 20px; margin: 0 5px; text-align: right; font-size: 8px;\">");
        }
        return commands;
    }

    @Override
    public StringBuffer processCustomCommand(StringBuffer template, Page page) {
        StringBuffer commands = new StringBuffer();
        StringBuffer command = null;
        if (Access.isGranted(page, actionPrintMultipleBarcode)) {
            command = new StringBuffer(template.toString());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintMultipleBarcode.getName());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print Multiple Barcode"));
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printMultipleBarcode('" + "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintMultipleBarcode.getName() + "', 'form-" + page.getMenu().getMenuName() + "')\"");
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/icon-barcode.png");
            commands.append(command.toString());
        }
        if (Access.isGranted(page, actionPrintAllBarcode)) {
            command = new StringBuffer(template.toString());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_LINK, "?m=" + page.getMenu().getMenuName() + "&a=" + actionPrintAllBarcode.getName());
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_TITLE, Dictionary.getValue(page, "Print All Barcode"));
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_PROPERTIES, " onclick=\"return __printAllBarcode()\"");
            Utility.replaceAll(command, Template.TABLE_COMMANDS_COMMAND_CUSTOM_IMAGE, "?image=/com/buanalintas/sandals/pos/item/icon-barcode-all.png");
            commands.append(command.toString());
        }
        return commands;
    }

    @Override
    public String doAction() {
        if (getAction().equals(actionPrintBarcode)) {
            String id = Utility.decode(Utility.getParameter(getRequest(), "id"));
            PosMasterItem itemBarcode = (PosMasterItem) getController().getData(id);
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            PosTransactionBarcode barcode = new PosTransactionBarcode();
            barcode.setBarcodeId(Sequence.next(barcode));
            barcode.setBarcodeBarcode(itemBarcode.getItemBarcode());
            barcode.setBarcodeInformation(itemBarcode.getItemModel());
            em.persist(barcode);
            em.getTransaction().commit();

        } else if (getAction().equals(actionPrintMultipleBarcode)) {
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            try {
                String[] ids = Utility.getPostParameterValues(this, "uniqId");
                for (String id : ids) {
                    PosMasterItem itemBarcode = (PosMasterItem) getController().getData(Utility.decode(id));
                    PosTransactionBarcode barcode = new PosTransactionBarcode();
                    barcode.setBarcodeId(Sequence.next(barcode));
                    barcode.setBarcodeBarcode(itemBarcode.getItemBarcode());
                    barcode.setBarcodeInformation(itemBarcode.getItemModel());
                    try {
                        barcode.setBarcodeQuantity(Integer.parseInt(Utility.getPostParameterEmpty(this, "barcode_quantity_" + id)));
                    } catch (Exception e) {
                    }
                    em.persist(barcode);
                }
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            em.getTransaction().commit();

        } else if (getAction().equals(actionPrintAllBarcode)) {
            EntityManager em = getEntityManager();
            em.getTransaction().begin();
            try {
                List<PosMasterItem> itemBarcode = em.createQuery("SELECT t FROM PosMasterItem t").setHint(Persistence.REFRESH_HINT, true).getResultList();
                for (PosMasterItem barcodes : itemBarcode) {
                    PosTransactionBarcode barcode = new PosTransactionBarcode();
                    barcode.setBarcodeId(Sequence.next(barcode));
                    barcode.setBarcodeBarcode(barcodes.getItemBarcode());
                    barcode.setBarcodeInformation(barcodes.getItemModel());
                    em.persist(barcode);
                }
            } catch (Exception e) {
                Logger.getInstance().log(e);
            }
            em.getTransaction().commit();
        }
        setEditActionRedirect("m=" + getMenu().getMenuName() + "&a=" + Action.EDIT.getName() + "&id=" + Utility.decode(Utility.getPostParameter(this, "id")));
        return super.doAction();
    }
    
    
}
